package com.killer.service;

import com.github.tobato.fastdfs.domain.MateData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Service
public class FastDFSClientService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String uploadFile(MultipartFile multipartFile) throws IOException {
        //获取原文件名
        String originName=multipartFile.getOriginalFilename();
        //获取文件字节
        byte[] bytes = multipartFile.getBytes();
        //文件大小
        long fileSize=bytes.length;
        //封装成字节数组流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        //获取文件扩展名
        String extName=StringUtils.substringAfterLast(originName, ".");
        System.out.println("原文件名:"+originName+"，扩展名:"+extName);
        //封装文件元数据
        Set<MateData> mateDataSet = new HashSet<MateData>();
        MateData fileNameMateData = new MateData("fileName", originName);
        MateData fileSizeMateData = new MateData("fileSize", String.valueOf(fileSize));
        mateDataSet.add(fileNameMateData);
        mateDataSet.add(fileSizeMateData);
        //文件上传
        StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, fileSize, extName, mateDataSet);
        System.out.println(storePath.getGroup()+":"+storePath.getPath()+":"+storePath.getFullPath());
        return storePath.getFullPath();
    }

    public byte[] downloadFile(String fileUrl){
        //group2/M00/00/00/akuKy2Akh7yAW6rkAAKf_Ups2iI742.png
        //获取组名  group2
        String groupName = fileUrl.substring(0, fileUrl.indexOf("/"));
        //获取路径名 /M00/00/00/akuKy2Akh7yAW6rkAAKf_Ups2iI742.png
        String pathName = fileUrl.substring(fileUrl.indexOf("/") + 1);
        System.out.println(pathName);
        //创建DownloadCallback的实现类,里面实现了recv()方法，返回字节数组
        DownloadByteArray downloadByteArray=new DownloadByteArray();
        //下载文件
        byte[] bytes=fastFileStorageClient.downloadFile(groupName, pathName, downloadByteArray);
        return bytes;
    }
}
